﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace ClientTest
{
    public class ClientControl
    {
        private Socket clientSocket;

        public ClientControl()
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void Connect(string ip, int port)
        {
            try
            {
                clientSocket.Connect(ip, port);
                Console.WriteLine("客户端连接成功");
                Task.Run( () => Receive() );
            }
            catch (Exception e)
            {
                Console.WriteLine("服务器端掉线");
            }

        }

        public void SendMsg(string message)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(message);
            clientSocket.Send(bytes);

        }

        private void Receive()
        {
            byte[] msg = new byte[1024];
            try
            {
                IPEndPoint point = clientSocket.LocalEndPoint as IPEndPoint;
                string ip = point.Address.ToString();
                string port = point.Port.ToString();
                int len = clientSocket.Receive(msg);
                string message = Encoding.UTF8.GetString(msg,0,len);
                Console.WriteLine($"{ip+port}:{message.Trim()}");
                Receive();
            }
            catch (Exception e)
            {
                Console.WriteLine("服务器掉线！！");
            }
            
        }
    }
}